package com.zhsj.OkeHomeConsumption.ui.activity.citypartner;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.InputType;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.hjq.bar.TitleBar;
import com.hjq.base.BaseDialog;
import com.hjq.dialog.DateDialog;
import com.hjq.dialog.MenuDialog;
import com.huantansheng.easyphotos.EasyPhotos;
import com.huantansheng.easyphotos.models.album.entity.Photo;
import com.zhsj.OkeHomeConsumption.R;
import com.zhsj.OkeHomeConsumption.adapter.GridViewAddImgesAdpter;
import com.zhsj.OkeHomeConsumption.common.Constants;
import com.zhsj.OkeHomeConsumption.common.MyActivity;
import com.zhsj.OkeHomeConsumption.empty.CityPartnerShopBean;
import com.zhsj.OkeHomeConsumption.empty.EnterpriseRecruitBean;
import com.zhsj.OkeHomeConsumption.empty.MerchantTypeBean;
import com.zhsj.OkeHomeConsumption.empty.SelectCityEnity;
import com.zhsj.OkeHomeConsumption.empty.UpLoadImgBean;
import com.zhsj.OkeHomeConsumption.helper.GlideEngine;
import com.zhsj.OkeHomeConsumption.ui.activity.citypartner.mvp.EnterpriseStoredetailsPresenter;
import com.zhsj.OkeHomeConsumption.ui.activity.citypartner.mvp.EnterpriseStoredetailsUIInterFace;
import com.zhsj.OkeHomeConsumption.ui.activity.wallet.ClearEditText;
import com.zhsj.OkeHomeConsumption.utils.JsonUtils;
import com.zhsj.OkeHomeConsumption.utils.SelectCityPicker;
import com.zhsj.OkeHomeConsumption.utils.UpLoadGridView;

import org.apache.commons.lang3.StringUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/*
 *装企招募--完善信息
 *
 * **/

public class EnterpriseStoredetailsActivity extends MyActivity implements EnterpriseStoredetailsUIInterFace {


    //公司名称
    @BindView(R.id.selet_name)
    ClearEditText seletName;

    //请选择所在城市
    @BindView(R.id.selet_city)
    ClearEditText seletCity;

    //公司地址
    @BindView(R.id.selet_address)
    ClearEditText seletAddress;

    //法定代表
    @BindView(R.id.selet_delegate)
    ClearEditText seletDelegate;

    //联系人
    @BindView(R.id.selet_contact)
    ClearEditText seletContact;

    //联系电话
    @BindView(R.id.selet_phone)
    ClearEditText seletPhone;

    //店铺面积
    @BindView(R.id.selet_area)
    ClearEditText seletArea;

    //公司成立时间
    @BindView(R.id.selet_craetetimer)
    ClearEditText seletCraetetimer;

    //营业执照
    @BindView(R.id.jingyingzhizhao)
    ImageView jingyingzhizhao;

    //门脸图
    @BindView(R.id.menliantu)
    UpLoadGridView menliantu;

    private GridViewAddImgesAdpter menliantu_gridViewAddImgesAdpter;
    private List<UpLoadImgBean> menlian_imageServiceList;

    @BindView(R.id.yingyezhihzao_lin)
    LinearLayout yingyezhihzaoLin;
    //提交
    @BindView(R.id.btn_test_login)
    Button btnTestLogin;

    //店内图
    @BindView(R.id.dianneihuanjing)
    UpLoadGridView dianneihuanjing;
    private GridViewAddImgesAdpter diannei_gridViewAddImgesAdpter;
    private List<UpLoadImgBean> diannei_imageServiceList;


    @BindView(R.id.tb_test_a_bar)
    TitleBar tb_test_a_bar;


    //门脸图 1  店内图2   营业执照3  许可证4 log5 背景6 店铺图7
    private int REQUEST_CODE_CHOOSE = -1;

    // 图片集合
    private List<File> datas_menlian = null;
    private List<UpLoadImgBean> imageServiceList = null;

    private EnterpriseStoredetailsPresenter minePersonPresenter;

    private ArrayList<SelectCityEnity> mSelectCityLists = null;


    private int proviceId = -1;//省
    private int mcityId = -1;//市
    private int districCountryId = -1;//区
    private int streetId;//街道


    private EnterpriseRecruitBean mCityPartnerShopbean;

    private Map<String, Object> mapjson_zhizhao;

    private EnterpriseRecruitBean mCityPartnerShop;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_enterprisestoredatails;
    }

    @Override
    protected int getTitleId() {
        return R.id.tb_test_a_bar;
    }

    @Override
    protected void initView() {
        minePersonPresenter = new EnterpriseStoredetailsPresenter(getActivity(), this);
        Bundle bundle = getIntent().getExtras();
        tb_test_a_bar.setTitle("完善信息");
        mCityPartnerShopbean = (EnterpriseRecruitBean) bundle.getSerializable("CityPartnerShop");
        minePersonPresenter.FindByUserIdGet(mCityPartnerShopbean.getUserId());
        datas_menlian = new ArrayList<>();
        imageServiceList = new ArrayList<>();
        diannei_imageServiceList = new ArrayList<>();
        menlian_imageServiceList = new ArrayList<>();

        seletCity.setEnabled(true);
        seletCity.setInputType(InputType.TYPE_NULL);
        seletCity.setFocusableInTouchMode(false);
        seletCity.setFocusable(false);
        seletCity.setCursorVisible(false);

        seletCraetetimer.setEnabled(true);
        seletCraetetimer.setInputType(InputType.TYPE_NULL);
        seletCraetetimer.setFocusableInTouchMode(false);
        seletCraetetimer.setFocusable(false);
        seletCraetetimer.setCursorVisible(false);
        mapjson_zhizhao = new HashMap<>();
    }

    @Override
    protected void initData() {
        menliantu_gridViewAddImgesAdpter = new GridViewAddImgesAdpter(menlian_imageServiceList, getActivity());
        menliantu_gridViewAddImgesAdpter.setMaxImages(2);
        menliantu.setAdapter(menliantu_gridViewAddImgesAdpter);
        menliantu.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
                //门脸图
                REQUEST_CODE_CHOOSE = 1;


                ShootingDialog(REQUEST_CODE_CHOOSE, 1);
            }
        });

        diannei_gridViewAddImgesAdpter = new GridViewAddImgesAdpter(diannei_imageServiceList, getActivity());
        diannei_gridViewAddImgesAdpter.setMaxImages(8);
        dianneihuanjing.setAdapter(diannei_gridViewAddImgesAdpter);
        dianneihuanjing.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
                //店面图
                REQUEST_CODE_CHOOSE = 2;
                ShootingDialog(REQUEST_CODE_CHOOSE, 8);
            }
        });

    }



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 101 && resultCode == RESULT_OK) {
            //返回对象集合：如果你需要了解图片的宽、高、大小、用户是否选中原图选项等信息，可以用这个
            ArrayList<Photo> resultPhotos = data.getParcelableArrayListExtra(EasyPhotos.RESULT_PHOTOS);
            datas_menlian.clear();
            for (int i = 0; i < resultPhotos.size(); i++) {
                datas_menlian.add(uri2File(resultPhotos.get(i).path));
            }
            minePersonPresenter.UploadPost(datas_menlian);
        } else if (requestCode == 9) {
            //营业执照
            if(data!=null){
                mapjson_zhizhao = (Map<String, Object>) data.getSerializableExtra("map");
            }
        }


    }


    @Override
    public void Update(String context) {
        try {
            JSONTokener jsonT = new JSONTokener(context);
            JSONObject jsonOBJ = (JSONObject) jsonT.nextValue();
            String code = jsonOBJ.optString("code");
            String message = jsonOBJ.optString("message");
            if (code.equals("N000000")) {
                toast("完善成功");
                finish();
            } else if (code.equals(Constants.STATUSTOKENERROR)) {
                // token过期
                if (!message.equals("null")) {
                    toast(message);
                }
            } else {
                if (!message.equals("null")) {
                    toast(message);
                }
            }
        } catch (JSONException ex) {
            Log.e("Update", "店铺维护与详情");
        }
    }


    @Override
    public void FindByUserIdGet(String context) {
        try {
            JSONTokener jsonT = new JSONTokener(context);
            JSONObject jsonOBJ = (JSONObject) jsonT.nextValue();
            String code = jsonOBJ.optString("code");
            String message = jsonOBJ.optString("message");
            if (code.equals("N000000")) {
                JSONObject jsonobj = jsonOBJ.optJSONObject("data");
                mCityPartnerShop = JsonUtils.object(jsonobj.toString(), EnterpriseRecruitBean.class);
                seletName.setText(mCityPartnerShop.getCompanyName());
                seletCity.setText(mCityPartnerShop.getConutyName());
                seletAddress.setText(mCityPartnerShop.getAddress());
                seletDelegate.setText(mCityPartnerShop.getLegalPerson());
                seletContact.setText(mCityPartnerShop.getCompanyContacts());
                seletPhone.setText(mCityPartnerShop.getMobile());
                seletArea.setText(mCityPartnerShop.getAera()+"");
                seletCraetetimer.setText(mCityPartnerShop.getCompanyCreateTime());

                proviceId = mCityPartnerShop.getProvince();//省
                mcityId = mCityPartnerShop.getCity();//市
                districCountryId = mCityPartnerShop.getConuty();//区
                Glide.with(this).load(mCityPartnerShop.getBusinessLicensePic()).placeholder(R.mipmap.tianjia_right).into(jingyingzhizhao);
                if (mCityPartnerShop.getHouseFacade() != null) {
                    menlian_imageServiceList.add(new UpLoadImgBean(mCityPartnerShop.getHouseFacade()));
                }

                if (mCityPartnerShop.getShopInsideImgs() != null) {
                    for (int i = 0; i < mCityPartnerShop.getShopInsideImgs().size(); i++) {
                        diannei_imageServiceList.add(new UpLoadImgBean(mCityPartnerShop.getShopInsideImgs().get(i)));
                    }
                }

                initData();
            } else if (code.equals(Constants.STATUSTOKENERROR)) {
                // token过期
                if (!message.equals("null")) {
                    toast(message);
                }
            } else {
                if (!message.equals("null")) {
                    toast(message);
                }
            }
        } catch (JSONException ex) {
            log("装企招募--维护");
        }
    }


    /**
     * 多张图片上传
     */
    @Override
    public void UploadPost(String context) {
        try {
            JSONTokener jsonT = new JSONTokener(context);
            JSONObject jsonOBJ = (JSONObject) jsonT.nextValue();
            String code = jsonOBJ.optString("code");
            String message = jsonOBJ.optString("message");
            if (code.equals("N000000")) {
                JSONArray jsondata = jsonOBJ.optJSONArray("data");
                if (imageServiceList.size() != 0) {
                    imageServiceList.clear();
                }
                imageServiceList = new Gson().fromJson(jsondata.toString(), new
                        TypeToken<ArrayList<UpLoadImgBean>>() {
                        }.getType());
                if (imageServiceList != null && imageServiceList.size() > 0) {
                    switch (REQUEST_CODE_CHOOSE) {
                        case 1:
                            //门脸数据
                            for (int i = 0; i < imageServiceList.size(); i++) {
                                menlian_imageServiceList.add(imageServiceList.get(i));
                            }
                            menliantu_gridViewAddImgesAdpter.notifyDataSetChanged(menlian_imageServiceList);
                            break;
                        case 2:
                            for (int i = 0; i < imageServiceList.size(); i++) {
                                diannei_imageServiceList.add(imageServiceList.get(i));
                            }
                            diannei_gridViewAddImgesAdpter.notifyDataSetChanged(diannei_imageServiceList);
                            break;

                    }
                    imageServiceList.clear();

                }
            } else if (code.equals(Constants.STATUSTOKENERROR)) {
                // token过期
                if (!message.equals("null")) {
                    toast(message);
                }
            } else {
                if (!message.equals("null")) {
                    toast(message);
                }
            }
        } catch (JSONException ex) {
            log("城市合伙人--- 多张图片上传");
        }
    }


    @Override
    public void CityListPsot(String context) {
        try {
            JSONTokener jsonT = new JSONTokener(context);
            JSONObject jsonOBJ = (JSONObject) jsonT.nextValue();
            String code = jsonOBJ.optString("code");
            String message = jsonOBJ.optString("message");
            if (code.equals("N000000")) {
                JSONArray jsonarr = jsonOBJ.optJSONArray("data");
                // 数据对接正常
                mSelectCityLists = new Gson().fromJson(jsonarr.toString(), new
                        TypeToken<ArrayList<SelectCityEnity>>() {
                        }.getType());
                getSelectCity(mSelectCityLists);

            } else if (code.equals(Constants.STATUSTOKENERROR)) {
                // token过期
                if (!message.equals("null")) {
                    toast(message);
                }
            } else {
                if (!message.equals("null")) {
                    toast(message);
                }
            }
        } catch (JSONException ex) {
            Log.e("CityListPsot", "获取城市列表");
        }
    }

    @OnClick({R.id.btn_test_login, R.id.yingyezhihzao_lin, R.id.selet_city, R.id.selet_craetetimer})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.yingyezhihzao_lin:
                //营业执
                Bundle bundle = new Bundle();
                bundle.putSerializable("CityPartnerShop", mCityPartnerShop);
                startActivityForResult(new Intent(this, BusinessLicenseActivity.class).putExtras(bundle), 9);
                break;
            case R.id.selet_city:
                //城市
                minePersonPresenter.CityListPsot();
                break;
            case R.id.selet_craetetimer:
                //成立时间
                //时间
                new DateDialog.Builder(this)
                        .setTitle("请选择日期")
                        .setListener(new DateDialog.OnListener() {
                            @Override
                            public void onSelected(Dialog dialog, int year, int month, int day) {
                                seletCraetetimer.setText(year + "-" + month + "-" + day);
                            }

                            @Override
                            public void onCancel(Dialog dialog) {

                            }
                        })
                        .show();
                break;

            case R.id.btn_test_login:
                //提交
                submit();
                break;
        }
    }

    /**
     * 图片选择
     */
    private void Pictureselection(int code, int max) {
        if (code == 0) {
            EasyPhotos.createCamera(this)//参数说明：上下文
                    .setFileProviderAuthority("com.zhsj.OkeHomeConsumption.fileprovider")//参数说明：见下方`FileProvider的配置`
                    .start(101);
        } else {
            EasyPhotos.createAlbum(this, false, GlideEngine.getInstance())//参数说明：上下文，是否显示相机按钮，[配置Glide为图片加载引擎](https://github.com/HuanTanSheng/EasyPhotos/wiki/12-%E9%85%8D%E7%BD%AEImageEngine%EF%BC%8C%E6%94%AF%E6%8C%81%E6%89%80%E6%9C%89%E5%9B%BE%E7%89%87%E5%8A%A0%E8%BD%BD%E5%BA%93)
                    .setCount(max)//参数说明：最大可选数，默认1
                    .setPuzzleMenu(false)
                    .start(101);
        }

    }

    /**
     * user转换为file文件
     * 返回值为file类型
     *
     * @param uri
     * @return
     */
    private File uri2File(String uri) {
        File file = new File(uri);
        return file;
    }

    private void ShootingDialog(final int code, final int max) {
        String[] arreaArr = getActivity().getResources().getStringArray(R.array.shooting_type);
        final List<String> shooting_type_list = Arrays.asList(arreaArr);
        new MenuDialog.Builder(this)
                .setCancel("取消") // 设置 null 表示不显示取消按钮
                //.setAutoDismiss(false) // 设置点击按钮后不关闭对话框
                .setList(shooting_type_list)
                .setListener(new MenuDialog.OnListener() {

                    @Override
                    public void onSelected(Dialog dialog, int position, String text) {
                        switch (position) {
                            case 0:
                                Pictureselection(position, max);
                                break;
                            case 1:
                                Pictureselection(position, max);
                                break;
                        }
                    }

                    @Override
                    public void onCancel(Dialog dialog) {
                        toast("取消了");
                    }
                })
                .setGravity(Gravity.BOTTOM)
                .setAnimStyle(BaseDialog.AnimStyle.BOTTOM)
                .show();
    }


    /**
     * 选择城市
     *
     * @param mSelectProviceEnities
     */
    private void getSelectCity(ArrayList<SelectCityEnity> mSelectProviceEnities) {
        SelectCityPicker selectCityPicker = new SelectCityPicker(getActivity(), mSelectProviceEnities);
        selectCityPicker.setHalfScreen(true);
        selectCityPicker.setCancelTextColor(R.color.colorAccent);
        selectCityPicker.setSubmitTextColor(R.color.colorAccent);
        selectCityPicker.setOnCitySelectListener(new SelectCityPicker.OnCitySelectListener() {
            @Override
            public void onCitySelect(String province, String city, String county, String town, int provinceId, int cityId, int countyId, int townId) {
                if (!province.equals("") && city.equals("") && county.equals("") && town.equals("")) {
                    seletCity.setText(province);
                } else if (!province.equals("") && !city.equals("") && !county.equals("") && town.equals("")) {
                    seletCity.setText(province);
                } else if (!province.equals("") && !city.equals("") && county.equals("") && town.equals("")) {
                    seletCity.setText(province + "-" + city);
                } else {
                    seletCity.setText(province + "-" + city + "-" + county + "-" + town);
                }
                proviceId = provinceId;
                mcityId = cityId;
                districCountryId = countyId;
                streetId = townId;
            }
        });
        selectCityPicker.show();
    }

    private void submit() {
        if (mapjson_zhizhao.size() == 0) {
            toast("请选择营业执照");
            return;
        }
        String shopname = seletName.getText().toString();
        if (shopname.equals("")) {
            toast("请输入公司名称");
            return;
        }

        String shopphone = seletPhone.getText().toString();
        if (shopphone.equals("")) {
            toast("请输入联系电话");
            return;
        }

        String Contact = seletContact.getText().toString();
        if (Contact.equals("")) {
            toast("请输入联系人");
            return;
        }
        String city = seletCity.getText().toString();
        if (city.equals("")) {
            toast("请选择城市");
            return;
        }
        String StoreAddress = seletAddress.getText().toString();
        if (StoreAddress.equals("")) {
            toast("请填写详细地址");
            return;
        }
        String Delegate = seletDelegate.getText().toString();
        if (Delegate.equals("")) {
            toast("请输入法定代表");
            return;
        }
        String area = seletArea.getText().toString();
        if (area.equals("")) {
            toast("请输入店铺面积");
            return;
        }
        String StoreProduct = seletCraetetimer.getText().toString();

        if (StoreProduct.equals("")) {
            toast("公司成立时间");
            return;
        }

        if (menlian_imageServiceList.size() == 0) {
            toast("请上传门脸图");
            return;
        }
        if (diannei_imageServiceList.size() == 0) {
            toast("请上传店内环境图");
            return;
        }

        Gson gson = new Gson();
        Map<String, Object> mapjson = new HashMap<>();
        mapjson.put("userId", mCityPartnerShopbean.getUserId());
        mapjson.put("audit", mCityPartnerShopbean.getAudit());
        mapjson.put("address", StoreAddress);//详细地址
        mapjson.put("aera", area);//店铺面积
        mapjson.put("companyName", shopname);//公司名称
        mapjson.put("businessLicenseLegalEntity", Delegate);//法定代表
        mapjson.put("companyContacts", Contact);//联系人
        mapjson.put("mobile", shopphone);//联系电话
        mapjson.put("cityName", city);//城市
        mapjson.put("companyCreateTime", StoreProduct);//时间
        mapjson.put("houseFacade", menlian_imageServiceList.get(0).getPhotoPath());//门脸图

        List<String> list2 = new ArrayList<>();
        for (int a = 0; a < diannei_imageServiceList.size(); a++) {
            list2.add(diannei_imageServiceList.get(a).getPhotoPath());
        }
        mapjson.put("shopInsideImgs", list2);//店内环境图

        mapjson.put("province", proviceId);//省id
        mapjson.put("city", mcityId);//市ID
        mapjson.put("conuty", districCountryId);//县ID
//        mapjson.put("streetId", streetId);//街道id

        //添加营业执照数据
        mapjson.putAll(mapjson_zhizhao);
        String lifeCityCopartnerDTO = gson.toJson(mapjson);//map转json字符串
        minePersonPresenter.Update(lifeCityCopartnerDTO);
    }

}

